package Model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import Controller.Tasker;
import Events.Appointment;
import Events.GenericEvent;
import Events.MoodleEvent;

import net.fortuna.ical4j.data.CalendarBuilder;
import net.fortuna.ical4j.data.ParserException;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;

public class DAOMoodleEvents{
	private String LINK = "http://cursos.iteso.mx/moodle/calendar/export_execute.php?" +
			"userid=15636&authtoken=0788a42fdaabeffadf3efc6b04b0aa07f19ca1bd&preset_what=" +
			"all&preset_time=recentupcoming";
	private String TEMP_FILE = "docs//hi.ics";
	private Tasker tasker;
	public DAOMoodleEvents(Tasker tasker)
	{
		this.tasker=tasker;
		//Thread t = new Thread(this);
		//t.start();
	}
//	public void run()
//	{
//		while(true)
//		{
//			
//		}
//	}
	public void update() {
		// TODO Auto-generated method stub
		try{
			URL ur = new URL(LINK);
	    	URLConnection urlCon = ur.openConnection();
	    	
	    	System.out.println(urlCon.getContentType());
	    	System.out.println(urlCon.getURL());
	    	InputStream in = urlCon.getInputStream();
	    	FileOutputStream fos = new FileOutputStream(new File(TEMP_FILE));
	    	byte[] array = new byte[50000]; // buffer temporal de lectura.
			int leido = in.read(array);
			while (leido > 0) {
				fos.write(array, 0, leido);
				leido = in.read(array);
			}
			
	    	fos.close();
	    	in.close();
	    	CalendarBuilder builder = new CalendarBuilder();

	    	Calendar calendar = builder.build(new FileInputStream(TEMP_FILE));
	    	ArrayList<GenericEvent> events = new ArrayList<GenericEvent>();
	    	for (@SuppressWarnings("rawtypes")
			Iterator i = calendar.getComponents().iterator(); i.hasNext();) {
	    	    Component component = (Component) i.next();
	    	    //No esta terminado falta acomadarlo bien
	    	    Appointment event = (Appointment)tasker.createEvent(0);
	    	    
	    	    
	    	    String idEvent = component.getProperties().getProperty("UID").getValue();
	    	    event.setSubject(component.getProperties().getProperty("SUMMARY").getValue());
	    	    event.setDescription(component.getProperties().getProperty("DESCRIPTION").getValue().replace("\n", "").replace(",", ""));
	    	    event.getParams().put("IDME", idEvent);
	    	    event.getParams().put("LM", parse(component.getProperties().getProperty("LAST-MODIFIED").getValue()));
	    	    
	    	    
	    	    
//	    	    Date d = parse(component.getProperties().getProperty("DTSTAMP").getValue());    
//	    	    event.setD_Final(d);
//	    	    event.setT_Final(d);

	    	    Date d2 = parse(component.getProperties().getProperty("DTSTART").getValue());
	    	    event.setD_Start(d2);
	    	    event.setT_Start(d2);
	    	    
	    	    events.add(event);
	    	    
	    	}
	    	tasker.updateEvents(events);
    	} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public Date parse(String date) throws ParseException
	{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
		return sdf.parse(date);
	}
}
